<!DOCTYPE html>
<html>
<head>
    <title>评论管理</title>
    {% include 'system/common/header.html' %}
</head>
<body class="ppress-container">
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form" action="">
            <div class="layui-form-item" style="margin-bottom: unset;">
                <label class="layui-form-label">评论状态</label>
                <div class="layui-input-inline">
                    <select name="status" lay-filter="status-filter">
                        <option value="">全部状态</option>
                        <option value="pending">待审核</option>
                        <option value="approved">已批准</option>
                        <option value="spam">垃圾评论</option>
                        <option value="trash">回收站</option>
                    </select>
                </div>
                <label class="layui-form-label">搜索</label>
                <div class="layui-input-inline">
                    <input type="text" name="search" placeholder="作者/内容/邮箱" class="layui-input">
                </div>
                <button class="layui-btn layui-btn-md" lay-submit lay-filter="comment-query">
                    <i class="layui-icon layui-icon-search"></i>
                    查询
                </button>
                <button type="reset" class="layui-btn layui-btn-primary layui-btn-md">
                    <i class="layui-icon layui-icon-refresh"></i>
                    重置
                </button>
                <button type="button" class="layui-btn layui-btn-normal layui-btn-md" onclick="initSampleData()">
                    <i class="layui-icon layui-icon-add-1"></i>
                    初始化示例数据
                </button>
            </div>
        </form>
    </div>
</div>

<div class="layui-card">
    <div class="layui-card-body">
        <table id="comment-table" lay-filter="comment-table"></table>
    </div>
</div>
</body>
{% include 'system/common/footer.html' %}

<script type="text/html" id="comment-toolbar">
    <div class="layui-btn-group">
        <button class="layui-btn layui-btn-primary layui-btn-sm" lay-event="batchApprove">
            <i class="layui-icon layui-icon-ok"></i>
            批量批准
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" lay-event="batchReject">
            <i class="layui-icon layui-icon-close"></i>
            批量驳回
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" lay-event="batchSpam">
            <i class="layui-icon layui-icon-close-fill"></i>
            标记垃圾
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" lay-event="batchTrash">
            <i class="layui-icon layui-icon-delete"></i>
            移至回收站
        </button>
    </div>
</script>

<script type="text/html" id="comment-bar">
    <div class="layui-btn-group">
        <button class="layui-btn layui-btn-xs layui-btn-primary" lay-event="reply">
            <i class="layui-icon layui-icon-reply-fill"></i> 回复
        </button>
        <button class="layui-btn layui-btn-xs layui-btn-primary" lay-event="edit">
            <i class="layui-icon layui-icon-edit"></i> 编辑
        </button>
        <button class="layui-btn layui-btn-xs layui-btn-warm" lay-event="spam">
            <i class="layui-icon layui-icon-close-fill"></i> 垃圾
        </button>
        <button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="remove">
            <i class="layui-icon layui-icon-delete"></i> 删除
        </button>
    </div>
</script>

<script type="text/html" id="comment-status">
    <span class="layui-badge" id="status-badge"></span>
</script>

<script type="text/html" id="comment-author">
    <div style="display: flex; align-items: center;">
        <div>
            <div style="font-weight: bold; color: #333;" id="author-name"></div>
        </div>
    </div>
</script>

<script type="text/html" id="comment-content">
    <div style="max-width: 300px;">
        <div style="margin-bottom: 5px; line-height: 1.4;" id="comment-text"></div>
        <div style="font-size: 12px; color: #999;" id="comment-time"></div>
    </div>
</script>

<script type="text/html" id="comment-article">
    <div>
        <div style="font-weight: bold; color: #333;" id="article-title"></div>
        <div style="font-size: 12px; color: #666;" id="article-id"></div>
    </div>
</script>

<script>
    layui.use(['table', 'form', 'jquery', 'popup', 'common'], function () {
        let table = layui.table
        let form = layui.form
        let $ = layui.jquery
        let popup = layui.popup

        let MODULE_PATH = '/admin/cms/comment/'

        let cols = [
            [
                {type: 'checkbox', fixed: 'left'},
                {title: '编号', field: 'id', width: 80, align: 'center'},
                {title: '作者', field: 'author', width: 150, templet: '#comment-author'},
                {title: '评论内容', field: 'content', templet: '#comment-content'},
                {title: '所属文章', field: 'article_title', width: 150, templet: '#comment-article'},
                {title: '状态', field: 'status', width: 100, templet: '#comment-status', align: 'center'},
                {title: '操作', toolbar: '#comment-bar', width: 280, align: 'center', fixed: 'right'}
            ]
        ]

        table.render({
            elem: '#comment-table',
            url: MODULE_PATH + 'list',
            page: true,
            cols: cols,
            skin: 'line',
            toolbar: '#comment-toolbar',
            defaultToolbar: [{
                layEvent: 'refresh',
                icon: 'layui-icon-refresh',
            }, 'filter', 'print', 'exports'],
            parseData: function(res) {
                return {
                    "code": res.code === 200 ? 0 : res.code,
                    "msg": res.msg,
                    "count": res.data.pagination.total,
                    "data": res.data.comments
                };
            },
            done: function(res, curr, count) {
                // 渲染完成后处理模板
                $('.layui-table-body tbody tr').each(function() {
                    let $tr = $(this);
                    let data = table.cache['comment-table'][$tr.data('index')];
                    if (data) {
                        // 处理状态徽章
                        let $statusBadge = $tr.find('#status-badge');
                        let statusClass = '';
                        let statusText = '';
                        switch(data.status) {
                            case 'pending':
                                statusClass = 'layui-bg-orange';
                                statusText = '待审核';
                                break;
                            case 'approved':
                                statusClass = 'layui-bg-green';
                                statusText = '已批准';
                                break;
                            case 'spam':
                                statusClass = 'layui-bg-red';
                                statusText = '垃圾';
                                break;
                            case 'trash':
                                statusClass = 'layui-bg-gray';
                                statusText = '回收站';
                                break;
                        }
                        $statusBadge.removeClass().addClass('layui-badge ' + statusClass).text(statusText);
                        
                        // 处理作者信息
                        let $avatar = $tr.find('#author-avatar');
                        let $name = $tr.find('#author-name');
                        let $email = $tr.find('#author-email');
                        let $ip = $tr.find('#author-ip');
                        
                        $avatar.text(data.author ? data.author.charAt(0).toUpperCase() : '?');
                        $name.text(data.author || '');
                        $email.text(data.email || '').toggle(!!data.email);
                        $ip.text(data.ip || '').toggle(!!data.ip);
                        
                        // 处理评论内容
                        let $text = $tr.find('#comment-text');
                        let $time = $tr.find('#comment-time');
                        $text.text(data.content || '');
                        $time.text(data.created_at || '');
                        
                        // 处理文章信息
                        let $articleTitle = $tr.find('#article-title');
                        let $articleId = $tr.find('#article-id');
                        $articleTitle.text(data.article_title || '未知文章');
                        $articleId.text('文章ID: ' + (data.article_id || '未知'));
                        
                        // 根据状态添加操作按钮
                        let $btnGroup = $tr.find('.layui-btn-group');
                        let statusBtn = '';
                        if (data.status === 'pending') {
                            statusBtn = '<button class="layui-btn layui-btn-xs layui-btn-normal" lay-event="approve"><i class="layui-icon layui-icon-ok"></i> 批准</button>';
                        } else if (data.status === 'approved') {
                            statusBtn = '<button class="layui-btn layui-btn-xs layui-btn-warm" lay-event="reject"><i class="layui-icon layui-icon-close"></i> 驳回</button>';
                        }
                        if (statusBtn) {
                            $btnGroup.prepend(statusBtn);
                        }
                    }
                });
            }
        })

        // 表格工具栏事件
        table.on('toolbar(comment-table)', function (obj) {
            if (obj.event === 'batchApprove') {
                batchUpdateComments('approve')
            } else if (obj.event === 'batchReject') {
                batchUpdateComments('reject')
            } else if (obj.event === 'batchSpam') {
                batchUpdateComments('spam')
            } else if (obj.event === 'batchTrash') {
                batchUpdateComments('trash')
            } else if (obj.event === 'refresh') {
                table.reload('comment-table')
            }
        })

        // 表格行工具事件
        table.on('tool(comment-table)', function (obj) {
            if (obj.event === 'approve') {
                updateCommentStatus(obj.data.id, 'approved')
            } else if (obj.event === 'reject') {
                updateCommentStatus(obj.data.id, 'pending')
            } else if (obj.event === 'reply') {
                replyComment(obj.data)
            } else if (obj.event === 'edit') {
                editComment(obj.data)
            } else if (obj.event === 'spam') {
                updateCommentStatus(obj.data.id, 'spam')
            } else if (obj.event === 'remove') {
                removeComment(obj)
            }
        })

        // 表单查询
        form.on('submit(comment-query)', function (data) {
            table.reload('comment-table', {where: data.field})
            return false
        })

        // 状态筛选
        form.on('select(status-filter)', function(data) {
            let statusValue = data.value;
            // 如果选择的是"全部状态"，则传递空字符串
            if (statusValue === '') {
                statusValue = '';
            }
            table.reload('comment-table', {where: {status: statusValue}})
        })

        // 更新评论状态
        function updateCommentStatus(commentId, status) {
            let statusText = {
                'approved': '批准',
                'pending': '驳回',
                'spam': '标记为垃圾',
                'trash': '移至回收站'
            }
            
            layer.confirm(`确定要${statusText[status]}该评论吗？`, {icon: 3, title: '提示'}, function (index) {
                layer.close(index)
                let loading = layer.load()
                $.ajax({
                    url: MODULE_PATH + 'update_status',
                    dataType: 'json',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        comment_id: commentId,
                        status: status
                    }),
                    success: function (result) {
                        layer.close(loading)
                        if (result.code === 200) {
                            layer.msg(result.msg, {icon: 1, time: 1000}, function () {
                                table.reload('comment-table')
                            })
                        } else {
                            layer.msg(result.msg, {icon: 2, time: 1000})
                        }
                    },
                    error: function() {
                        layer.close(loading)
                        layer.msg('操作失败', {icon: 2, time: 1000})
                    }
                })
            })
        }

        // 批量更新评论
        function batchUpdateComments(action) {
            let data = table.checkStatus('comment-table').data
            if (data.length === 0) {
                layer.msg('未选中数据', {icon: 3, time: 1000})
                return false
            }
            
            let actionText = {
                'approve': '批量批准',
                'reject': '批量驳回',
                'spam': '批量标记为垃圾',
                'trash': '批量移至回收站'
            }
            
            layer.confirm(`确定要${actionText[action]}选中的评论吗？`, {icon: 3, title: '提示'}, function (index) {
                layer.close(index)
                let loading = layer.load()
                
                let commentIds = data.map(item => item.id)
                $.ajax({
                    url: MODULE_PATH + 'batch_update',
                    data: JSON.stringify({
                        comment_ids: commentIds,
                        action: action
                    }),
                    dataType: 'json',
                    type: 'POST',
                    contentType: 'application/json',
                    success: function (result) {
                        layer.close(loading)
                        if (result.code === 200) {
                            popup.success(result.msg, function () {
                                table.reload('comment-table')
                            })
                        } else {
                            popup.failure(result.msg)
                        }
                    },
                    error: function() {
                        layer.close(loading)
                        layer.msg('操作失败', {icon: 2, time: 1000})
                    }
                })
            })
        }

        // 回复评论
        function replyComment(commentData) {
            layer.prompt({
                title: '回复评论',
                formType: 2,
                value: '',
                area: ['400px', '200px']
            }, function(value, index) {
                if (value.trim()) {
                    $.ajax({
                        url: MODULE_PATH + 'reply',
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        data: JSON.stringify({
                            parent_id: commentData.id,
                            content: value,
                            article_id: commentData.article_id || 1
                        }),
                        success: function(result) {
                            if (result.code === 200) {
                                layer.msg('回复成功', {icon: 1, time: 1500})
                                layer.close(index)
                                table.reload('comment-table')
                            } else {
                                layer.msg(result.msg, {icon: 2, time: 2000})
                            }
                        },
                        error: function() {
                            layer.msg('回复失败', {icon: 2, time: 2000})
                        }
                    })
                }
            })
        }

        // 编辑评论
        function editComment(commentData) {
            layer.prompt({
                title: '编辑评论',
                formType: 2,
                value: commentData.content,
                area: ['400px', '200px']
            }, function(value, index) {
                if (value.trim() && value !== commentData.content) {
                    layer.msg('编辑功能待实现', {icon: 1, time: 1500})
                    layer.close(index)
                }
            })
        }

        // 删除评论
        function removeComment(obj) {
            layer.confirm('确定要删除该评论吗？', {icon: 3, title: '提示'}, function (index) {
                layer.close(index)
                let loading = layer.load()
                $.ajax({
                    url: MODULE_PATH + 'remove/' + obj.data.id,
                    dataType: 'json',
                    type: 'DELETE',
                    success: function (result) {
                        layer.close(loading)
                        if (result.code === 200) {
                            layer.msg(result.msg, {icon: 1, time: 1000}, function () {
                                obj.del()
                            })
                        } else {
                            layer.msg(result.msg, {icon: 2, time: 1000})
                        }
                    },
                    error: function() {
                        layer.close(loading)
                        layer.msg('删除失败', {icon: 2, time: 1000})
                    }
                })
            })
        }

        // 初始化示例数据
        window.initSampleData = function() {
            layer.confirm('确定要初始化示例评论数据吗？这将添加5条测试评论。', {
                title: '确认初始化',
                btn: ['确定', '取消']
            }, function(index) {
                $.ajax({
                    url: MODULE_PATH + 'init_sample_data',
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                })
                .then(function(result) {
                    if (result.code === 200) {
                        layer.msg(result.msg, {icon: 1, time: 2000})
                        table.reload('comment-table')
                    } else {
                        layer.msg(result.msg, {icon: 2, time: 2000})
                    }
                })
                .catch(function() {
                    layer.msg('初始化数据失败', {icon: 2, time: 2000})
                });
                layer.close(index)
            })
        }
    })
</script>
</html>